#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import traceback

from common.log_handler import logger


def socket_send(ip, port, request_msg, sock, timeout=7200):
    sock.settimeout(timeout)
    sock.connect((ip, port))
    response_msg = ""
    sock.send(request_msg.encode("utf-8"))
    while True:
        data = sock.recv(102400).decode('utf-8')
        response_msg += data
        if not data:
            break
    return response_msg


class TSLInterface(object):
    """
    backend server interface
    """

    def __init__(self, username, password, ip, port):
        self.username = username
        self.password = password
        self.ip = ip
        self.port = port

    def __send_msg(self, message):
        """
        send message to server
        :param message:
        :return:
        """
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        msg = "username:" + self.username + ";password:" + self.password + ";massageBody:" + message
        length = len(msg) + 8
        send_message = (8 - len(str(length))) * "0" + str(length) + msg
        try:
            logger.info('[reqmsg]{}'.format(send_message))
            response = socket_send(self.ip, self.port, send_message, self.sock, timeout=7200)
            logger.info('[rspmsg]{}'.format(response))
            self.sock.close()
            return response
        except socket.error:
            logger.error(traceback.format_exc())
            self.sock.close()
            return False
        except:
            logger.error(traceback.format_exc())
            return False

    def TSL_Login(self):
        """
        :param status: 0 表示注册, 1,表示登录
        :return:
        """
        request_message = "TSL_Login," + "%s,%s" % (self.username, self.password)
        result = self.__send_msg(request_message)[-1]
        return result

    def TSL_Get_User_Dec_By_Username(self, username):
        """
        根据用户名获取用户信息
        :param username:
        :return:
        """
        return "admin"

    def TSL_Get_Camara_List_By_Attribute(self, attributeString):
        requestMessage = "TSL_Get_Camara_List_By_Attribute," + "keywords=%s" % (attributeString)
        result = self.__send_msg(requestMessage)
        resultCode, resultInfo = result.split("::")
        if resultCode[-1] != "0":
            return ("1", [])
        else:
            deviceList = []
            deviceStrList = resultInfo.split("||")
            for device in deviceStrList:
                deviceInfoList = device.split(",")
                deviceList.append(deviceInfoList)
            return deviceList


if __name__ == "__main__":
    print(TSLInterface('admin', "123456", '127.0.0.1', 9999).TSL_Get_Camara_List_By_Attribute(""))
